﻿using Newtonsoft.Json.Linq;
using NLog;
using System.IO;

namespace GBT.Tool.Core
{
    internal class Configuration
    {
        private Logger logger = LogManager.GetCurrentClassLogger();
        //JSON配置文件目录
        string strpath = Directory.GetCurrentDirectory() + @"\Configuration.json";

        /// <summary>
        /// 文件写入（创建文件并写入。如文件存在，则覆盖该文件，写入完毕关闭文件）
        /// </summary>
        /// <param name="content">写入内容</param>
        private void WriteAll(string content)
        {
            File.WriteAllText(strpath, content);
        }

        /// <summary>
        /// 读取文件（打开文件并读取文件的所有内容，读取完毕关闭文件）
        /// </summary>
        /// <returns></returns>
        private string ReadAll()
        {
            if (!File.Exists(strpath))
            {
                FileStream fs = new FileStream(strpath, FileMode.Create, FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(fs);
                sw.Write("{}");
                sw.Flush();
                sw.Close();
            }
            return File.ReadAllText(strpath);
        }

        /// <summary>
        /// 判断配置文件是否为空
        /// </summary>
        /// <returns></returns>
        internal bool IsFileEmpty()
        {
            if (ReadAll() == "{}")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 写入配置
        /// </summary>
        /// <param name="joConfig">配置JSON</param>
        internal void WriteConfiguration(JObject joConfig)
        {
            string config = joConfig.ToString();
            WriteAll(config);
        }

        /// <summary>
        /// 读取配置信息
        /// </summary>
        /// <returns></returns>
        internal JObject ReadConfiguration()
        {
            JObject joConfig = JObject.Parse(ReadAll());
            return joConfig;
        }
    }
}